<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

/**
*
* @package MediaLibrary
* @copyright 2009 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru);Rob de Cleen(rob@decleen.com)
* Homepage: http://www.joomlawebserver.com
* @version: 1.5.3 Basic $
*
**/


$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path']	= JPATH_SITE;
require_once($mosConfig_absolute_path."/administrator/components/com_medialibrary/compat.joomla1.5.php");

// load language
if (file_exists($mosConfig_absolute_path."/components/com_medialibrary/language/{$mosConfig_lang}.php" ))
 {
  include_once($mosConfig_absolute_path."/components/com_medialibrary/language/{$mosConfig_lang}.php" );
 } 
else 
 {
  include_once($mosConfig_absolute_path."/components/com_medialibrary/language/english.php" );
 }


/** load the html drawing class */
require_once( $mainframe->getPath( 'front_html' ) );
require_once( $mainframe->getPath( 'class' ) );
require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary_game.class.php");
require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary_music.class.php");
require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary_book.class.php");
require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary_video.class.php");
require_once ($mosConfig_absolute_path."/components/com_medialibrary/medialibrary.class.lend_request.php");
require_once ($mosConfig_absolute_path."/components/com_medialibrary/medialibrary.class.lend.php");
require_once ($mosConfig_absolute_path."/components/com_medialibrary/medialibrary.class.review.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_medialibrary/admin.medialibrary.class.others.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_medialibrary/admin.medialibrary.class.conf.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_medialibrary/admin.medialibrary.class.ws.php");

$GLOBALS['medialibrary_configuration'] = $medialibrary_configuration;

$mainframe->setPageTitle( _MEDIALIBRARY_TITLE );

$task = trim( mosGetParam( $_REQUEST, 'task', "" ) );
$id = intval( mosGetParam( $_REQUEST, 'id', 0 ) );
$catid = intval(mosGetParam( $_REQUEST, 'catid', 0 ) );
$bids = mosGetParam($_REQUEST, 'bid', array(0));

// paginations
$intro    =  $medialibrary_configuration['page']['items']; // page length

if ($intro) 
 {
  $GLOBALS['paginations'] = 1;
  $limit    = intval( mosGetParam( $_REQUEST, 'limit', $intro ) );
  $GLOBALS['limit'] = $limit;
 
  $limitstart = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
  
  $GLOBALS['limitstart'] = $limitstart;

  $total    = 0;
  $LIMIT = 'LIMIT '.$limitstart.','.$limit;
 }
 
else 
{
  $GLOBALS['paginations'] = 0;
  $LIMIT    = '';
}

            

if($medialibrary_configuration['debug'] == '1'){
  echo "Task: ".$task . "<br />";
  print_r($_POST);
  echo "<hr /><br />";
}


switch ($task)
{
	case 'show_search':
	showSearchMedias( $option, $catid, $option );
	break;
	
	case 'search':
	searchMedias( $option, $catid, $option );
	break;

	case 'view':
	showItem( $id, $catid );
	break;

	case 'review':
	reviewMedia( $option );
	break;
	
	case 'showCategory':
	//if no category is selected show default action
	if ( $catid ) 
  {
	  showCategory( $catid );
	} else
  {
	  $task = "xxx";
	}
	break;

	case 'lend_request':
		showLendRequest( $option, $bids );
	break;
	
	case 'save_lend_request':
		saveLendRequest( $option, $bids );
	break;
	
	case 'mdownload':
		mydownload($id);
	break;

	case 'downitsf':
		downloaditself($id);	
	break;	

	default:
	  listCategories($catid);
	break;
	

}

function output_file($file, $name, $mime_type='')
{
 /*
 This function takes a path to a file to output ($file), 
 the filename that the browser will see ($name) and 
 the MIME type of the file ($mime_type, optional).
 
 If you want to do something on download abort/finish,
 register_shutdown_function('function_name');
 */
 if(!is_readable($file)) die('File not found or inaccessible!');
 
 $size = filesize($file);
 $name = rawurldecode($name);
 
 /* Figure out the MIME type (if not specified) */
 $known_mime_types=array(
  "pdf" => "application/pdf",
  "txt" => "text/plain",
  "html" => "text/html",
  "htm" => "text/html",
  "exe" => "application/octet-stream",
  "zip" => "application/zip",
  "doc" => "application/msword",
  "xls" => "application/vnd.ms-excel",
  "ppt" => "application/vnd.ms-powerpoint",
  "gif" => "image/gif",
  "png" => "image/png",
  "jpeg"=> "image/jpg",
  "jpg" =>  "image/jpg",
  "php" => "text/plain"
 );
 
 if($mime_type==''){
   $file_extension = strtolower(substr(strrchr($file,"."),1));
   if(array_key_exists($file_extension, $known_mime_types)){
    $mime_type=$known_mime_types[$file_extension];
   } else {
    $mime_type="application/force-download";
   };
 };
 
 ob_end_clean(); //turn off output buffering to decrease cpu usage
 
 // required for IE, otherwise Content-Disposition may be ignored
 if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');
 
// header('Content-Type: ' . $mime_type);
header('Content-Type: application/force-download');
// header('Content-Disposition: attachment; filename="'.$name.'"');
 header("Content-Disposition: inline; filename=$name");
 header("Content-Transfer-Encoding: binary");
 header('Accept-Ranges: bytes');
 
 /* The three lines below basically make the 
    download non-cacheable */
 header("Cache-control: private");
 header('Pragma: private');
 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
 
 // multipart-download and download resuming support
 if(isset($_SERVER['HTTP_RANGE']))
 {
  list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
  list($range) = explode(",",$range,2);
  list($range, $range_end) = explode("-", $range);
  $range=intval($range);
  if(!$range_end) {
    $range_end=$size-1;
  } else {
    $range_end=intval($range_end);
  }
 
  $new_length = $range_end-$range+1;
  header("HTTP/1.1 206 Partial Content");
  header("Content-Length: $new_length");
//  header("Content-Range: bytes $range-$range_end/$size");
 } else {
  $new_length=$size;
  header("Content-Length: ".$size);
 }


 $chunksize = 1*(1024*1024); //you may want to change this
 $bytes_send = 0;
 if ($file = fopen($file, 'r'))
 {
  if(isset($_SERVER['HTTP_RANGE']))
  fseek($file, $range);
 
  while(!feof($file) && 
    (!connection_aborted()) && 
    ($bytes_send<$new_length)
        )
  {
    $buffer = fread($file, $chunksize);
    print($buffer); //echo($buffer); // is also possible
    flush();
    $bytes_send += strlen($buffer);
  }
  fclose($file);
 } else die('Error - can not open file.');

  die();

}



function mydownload($id)
{
    downloaditself($id);
}
function downloaditself($idt)
	{
    global $database,$my;
    global $medialibrary_configuration;
    global $mosConfig_absolute_path;
    
	  if(array_key_exists("id",$_POST )  )
		  $id=$_POST['id'];
	  else
		  $id=$idt;
  
//	  $query = "SELECT * from #__medialibrary where id = ".$id;
//	  $database->setQuery( $query );
//	  $book = $database->loadObjectList();

		//load the Media
		$media = new mosMediaLibrary( $database );
		$media->load($id);
		
		$media_type_class = '';
		switch ($media->media_type)
		{
      case 'book':
        $media_type_class = new mosMedialibrary_book($database);
        $media_type_class->load($media->media_id);
        $media_type_class->emediaURL = $media_type_class->ebookURL;
        break;
      case 'video':
        $media_type_class = new mosMedialibrary_video($database);
        $media_type_class->load($media->media_id);
        $media_type_class->emediaURL = $media_type_class->evideoURL;
        break;
      case 'music':
        $media_type_class = new mosMedialibrary_music($database);
        $media_type_class->load($media->media_id);
        $media_type_class->emediaURL = $media_type_class->emusicURL;
        break;
      case 'game':
        $media_type_class = new mosMedialibrary_game($database);
        $media_type_class->load($media->media_id);
        $media_type_class->emediaURL = $media_type_class->egameURL;
        break;
		}


		if(strpos($_SERVER["HTTP_REFERER"],$_SERVER['SERVER_NAME']) !== false )
		{
		 $name = explode('/',$media_type_class->emediaURL);

		 $file_path=$mosConfig_absolute_path.$medialibrary_configuration['emedias']['location']
        .$name[count($name)-1];

		 set_time_limit(0);	
		 output_file($file_path, $name[count($name)-1]);
		 exit;
		}
		else
		{
      header("Cache-control: private");
      header('Pragma: private');
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
      header("HTTP/1.1 301 Moved Permanently");
      header('Content-Type: application/force-download');
      header("Location: ".$media_type_class->ebookURL);
      exit;
		}
	}

function saveLendRequest($option, $bids){
	global $mainframe, $database, $my, $Itemid, $acl;
	global $medialibrary_configuration, $mosConfig_mailfrom;
	

  if( !($medialibrary_configuration['lendstatus']['show'] )  ||
	      !checkAccess($medialibrary_configuration['lendrequest']['registrationlevel'],
        'RECURSE', userGID($my->id), $acl))
  {
		  echo _MEDIALIBRARY_NOT_AUTHORIZED;
		  return;
  }
	
	$help = array();	
	foreach($bids as $bid){
		$lend_request = new mosMediaLibrary_lend_request($database); 
		if (!$lend_request->bind($_POST)) {
			echo "<script> alert('".$lend_request->getError()."'); window.history.go(-1); </script>\n";
			exit ();
		}
		$lend_request->lend_request = date("Y-m-d H:i:s");
		$lend_request->fk_mediaid = $bid;
		
		if (!$lend_request->check()) {
			echo "<script> alert('".$lend_request->getError()."'); window.history.go(-1); </script>\n";
			exit ();
		}
		if (!$lend_request->store()) {
			echo "<script> alert('".$lend_request->getError()."'); window.history.go(-1); </script>\n";
			exit ();
		}

		    
    $lend_request->checkin();
		array_push($help, $lend_request);
	}

	
	$currentcat = NULL;
	// Parameters
	$menu =& new mosMenu( $database );
	$menu->load( $Itemid );
	$params =& new mosParameters( $menu->params );
	$params->def( 'header', $menu->name );
	$params->def( 'pageclass_sfx', '' );
	//
	$params->def( 'show_search', '1' );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

	$currentcat->descrip = _MEDIALIBRARY_LABEL_LEND_REQUEST_THANKS;
	
	// page image
	$currentcat->img = "./components/com_medialibrary/images/medialibrary_logo.png";

	$currentcat->header = $params->get( 'header' );
	
	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );


	HTML_medialibrary :: showLendRequestThanks($params, $currentcat);
	
}

function showLendRequest($option,$bid)
{
	global $mainframe, $database, $my, $Itemid, $acl;
	global $medialibrary_configuration;

  if( !( $medialibrary_configuration['lendstatus']['show'] )  ||
		!checkAccess($medialibrary_configuration['lendrequest']['registrationlevel'],'RECURSE', userGID($my->id), $acl))
  {
    echo _MEDIALIBRARY_NOT_AUTHORIZED;
	  return;
  }
		
	$bids = implode(',', $bid);
	
	// getting all medias for this category
//	$query = "SELECT * FROM #__medialibrary"
//		. "\nWHERE id IN (" .  $bids . ") AND fk_lendid = 0"
//		. "\nORDER BY catid, ordering";

  $query = "SELECT library.id, library.media_type, library.media_id," .
     " library.hits, library.checked_out, library.catid, ".
     " library.fk_lendid,library.date," .
     " other_table.id as media_type_id, other_table.title as title, other_table.rating as rating, " .
     " other_table.URL as URL, other_table.imageURL as imageURL " .
     " FROM #__medialibrary AS library " .
     " LEFT JOIN (SELECT id,title,rating,URL,imageURL,'game' as type FROM #__medialibrary_game ".
     " UNION all SELECT id,title,rating,URL,imageURL,'music' as type FROM #__medialibrary_music " .
     " UNION all SELECT id,title,rating,URL,imageURL,'book' as type FROM #__medialibrary_book " .
     " UNION all SELECT id,title,rating,URL,imageURL,'video' as type FROM #__medialibrary_video) " .
     " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
	 " WHERE library.id IN (" .  $bids . ") AND fk_lendid = 0" .
	 " ORDER BY library.catid, ordering";
		
	$database->setQuery( $query );
	$medias = $database->loadObjectList();
	
	$currentcat = NULL;
	// Parameters
	$menu =& new mosMenu( $database );
	$menu->load( $Itemid );
	$params =& new mosParameters( $menu->params );
	$params->def( 'header', _MEDIALIBRARY_DESC_TITLE );
	//$params->def( 'header', $menu->name );
	$params->def( 'pageclass_sfx', '' );
	$params->def( 'show_lendstatus', 1 );
	$params->def( 'show_lendrequest', 1 );
	$params->def( 'lend_save', 1); 
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );


	// page description
	$currentcat->descrip = _MEDIALIBRARY_DESC_LEND;
	
	// page image
	$currentcat->img = './components/com_medialibrary/images/medialibrary_logo.png';
	$currentcat->align = 'right';

	$currentcat->header = $params->get( 'header' );
	//$currentcat->header = $currentcat->header . ": " . $category->title;
	
	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

	HTML_medialibrary :: showLendRequest($medias, $currentcat, $params, $tabclass, $catid, $sub_categories,false);
}


/**
 * comments for registered users
 */
function reviewMedia()
{

	global $mainframe, $database, $my, $Itemid, $acl,
     $medialibrary_configuration, $mosConfig_absolute_path, $catid;
	global $mosConfig_mailfrom;
	

  if(!($medialibrary_configuration['reviews']['show'])  ||
    !checkAccess($medialibrary_configuration['reviews']['registrationlevel'],
    'RECURSE', userGID($my->id), $acl)) 
  {
		echo _MEDIALIBRARY_NOT_AUTHORIZED;
	 	return;
	}	
	
  $review = new mosMediaLibrary_review($database);
	$review->date = date("Y-m-d H:i:s");
	$review->fk_userid = $my->id;
	

	if (!$review->bind($_POST)) {
		echo "<script> alert('".$review->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}
	
	if (!$review->check()) {
		echo "<script> alert('".$review->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}
	if (!$review->store()) {
		echo "<script> alert('".$review->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}


	//showing the original entries
	mosRedirect("?option=com_medialibrary&amp;task=view&amp;catid=".$_POST['catid']."&amp;id=$review->fk_mediaid&amp;Itemid=$Itemid");

}


//this function check - is exist books in this folder and folders under this category 
function is_exist_curr_and_subcategory_medias($catid) {
		global $database, $my; 

		$query = "SELECT *, COUNT(a.id) AS numlinks FROM #__categories AS cc" 
			. "\n LEFT JOIN #__medialibrary AS a ON a.catid = cc.id" 
			. "\n WHERE a.published='1' AND a.approved='1' AND section='com_medialibrary' AND cc.id='$catid' AND cc.published='1' AND cc.access <= '$my->gid'" 
			. "\n GROUP BY cc.id" 
			. "\n ORDER BY cc.ordering"; 
		$database->setQuery( $query ); 
		$categories = $database->loadObjectList();
		if( count($categories) != 0 ) return true;

		$query = "SELECT id " 
			. "FROM #__categories AS cc " 
			. " WHERE section='com_medialibrary' AND parent_id='$catid' AND published='1' AND access<='$my->gid'"; 
		$database->setQuery( $query ); 
		$categories = $database->loadObjectList();
 
		if( count($categories) == 0 ) return false;

		foreach($categories as $k) {
			if( is_exist_curr_and_subcategory_medias($k->id) ) return true;
		}
		return false; 
}//end function

//*****************************************************************************

//this function check - is exist folders under this category 
function is_exist_subcategory_books($catid) {
		global $database, $my; 

		$query = "SELECT *, COUNT(a.id) AS numlinks FROM #__categories AS cc" 
			. "\n LEFT JOIN #__medialibrary AS a ON a.catid = cc.id" 
			. "\n WHERE a.published='1' AND a.approved='1' AND section='com_medialibrary' AND parent_id='$catid' AND cc.published='1' AND cc.access <= '$my->gid'" 
			. "\n GROUP BY cc.id" 
			. "\n ORDER BY cc.ordering"; 
		$database->setQuery( $query ); 
		$categories = $database->loadObjectList();
		if( count($categories) != 0 ) return true;

		$query = "SELECT id " 
			. "FROM #__categories AS cc " 
			. " WHERE section='com_medialibrary' AND parent_id='$catid' AND published='1' AND access<='$my->gid'"; 
		$database->setQuery( $query ); 
		$categories = $database->loadObjectList();
 
		if( count($categories) == 0 ) return false;

		foreach($categories as $k) {
			if( is_exist_subcategory_books($k->id) ) return true;
		}
		return false; 
}//end function


/**
 * This function is used to show a list of all books
 */
function listCategories( $catid ) 
{
//echo $catid ; exit;

	global $mainframe, $database, $my, $acl;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid, $medialibrary_configuration;

	$query = "select c.id, c.parent_id, c.title, c.image, d.medias, '0' as display from (select id, parent_id, title, image from #__categories where section='com_medialibrary' ORDER BY ordering ) as c left join ( select a.id as id, count(b.id) as medias  from #__categories as a, #__medialibrary as b  where b.catid=a.id and b.published=1 GROUP BY a.id) as d  on  c.id = d.id;";


	$database->setQuery( $query ); 
	$cat_all = $database->loadObjectList();

	for ($i = 0; $i < count($cat_all); $i++) {
		if (is_exist_curr_and_subcategory_medias($cat_all[$i]->id)) $cat_all[$i]->display = 1;
	}
//print_r($cat_all);exit;
	$currentcat = NULL;
	// Parameters
	$menu =& new mosMenu( $database );
	$menu->load( $Itemid );
	$params =& new mosParameters( $menu->params );
	$params->def( 'header', $menu->name );
	$params->def( 'pageclass_sfx', '' );
	$params->def( 'show_search', '1' );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

	// page header
	$currentcat->header = $params->get( 'header' );

	//add for show in category picture
	if(($medialibrary_configuration['cat_pic']['show'])) $params->def( 'show_cat_pic', 1 );

	// page description
	$currentcat->descrip = _MEDIALIBRARY_DESC;

	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

	HTML_medialibrary::showCategories($params, $cat_all, $catid, $tabclass, $currentcat);
}



function constructPathway($cat){
    global $mainframe, $database, $option, $Itemid,$mosConfig_absolute_path;

    $query = "SELECT * FROM #__categories WHERE section = 'com_medialibrary' AND published = 1";
    $database->setQuery($query);
    $rows = $database->loadObjectlist('id');
    $pid = $cat->id;
    $pathway = array();
    $pathway_name = array();
    while($pid != 0){

      $cat = @$rows[$pid];

      $pathway[] =  sefRelToAbs('index.php?option=' . $option . '&task=showCategory&catid=' . @$cat->id . '&Itemid=' . $Itemid);
      $pathway_name[] =  @$cat->name  ;
      $pid = @$cat->parent_id;
    }

    $pathway = array_reverse($pathway);
    $pathway_name = array_reverse($pathway_name);

    for($i=0,$n=count($pathway);$i<$n;$i++){
      $mainframe->appendPathWay($pathway_name[$i],$pathway[$i] );
//echo $pathway[$i] ."::";
    }
//exit;
}


/**
 * This function is used to show a list of all books
 */
function showCategory( $catid )
{

	global $mainframe, $database, $acl, $my;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid, $medialibrary_configuration;

	// getting all medias for this category
/*	$query = "SELECT id, isbn, authors, rating, title, catid, fk_lendid, date, hits, URL,imageURL "
      ." FROM #__medialibrary"
		. " WHERE catid = '$catid' AND published='1' AND approved='1' AND archived=0"
		. " ORDER BY ordering";*/
  $query = "SELECT library.id, library.media_type, library.media_id," .
     " library.hits, library.checked_out, library.catid, ".
     " library.fk_lendid,library.date," .
     " other_table.id as media_type_id, other_table.title as title, other_table.rating as rating, " .
     " other_table.URL as URL, other_table.imageURL as imageURL " .
     " FROM #__medialibrary AS library " .
     " LEFT JOIN (SELECT id,title,rating,URL,imageURL,'game' as type FROM #__medialibrary_game ".
     " UNION all SELECT id,title,rating,URL,imageURL,'music' as type FROM #__medialibrary_music " .
     " UNION all SELECT id,title,rating,URL,imageURL,'book' as type FROM #__medialibrary_book " .
     " UNION all SELECT id,title,rating,URL,imageURL,'video' as type FROM #__medialibrary_video) " .
     " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
     " WHERE catid = '$catid' AND published='1' AND approved='1' AND archived=0" .
     " ORDER BY ordering";

	$database->setQuery( $query );
	$medias = $database->loadObjectList();	
	
	//getting the current category informations
	$query = "SELECT * FROM #__categories WHERE id='$catid'";
	$database->setQuery( $query );	
	$category = $database->loadObjectList();
	$category = $category[0];

	$query = "select c.id, c.parent_id, c.title, c.image, d.medias, '0' as display from (select id, parent_id, title, image from #__categories where section='com_medialibrary' ) as c left join ( select a.id as id, count(b.id) as medias  from #__categories as a, #__medialibrary as b  where b.catid=a.id and b.published=1 GROUP BY a.id) as d  on  c.id = d.id;";

//   $selectstring = "SELECT library.id, library.media_type, library.media_id," .
//     "cc.title AS category, library.published, library.hits, library.checked_out, library.catid, ".
//     " library.informationFrom, l.id as lendid, l.lend_from as lend_from, " .
//     " l.lend_return as lend_return, " .
//     " l.lend_until as lend_until ," .
//     " u.name AS editor, " .
//     " other_table.id as media_type_id,  other_table.title as title  " .
//     " FROM #__medialibrary AS library " .
//     " LEFT JOIN #__categories AS cc ON cc.id = library.catid "  .
//     " LEFT JOIN #__medialibrary_lend AS l ON library.fk_lendid = l.id " .
//     " LEFT JOIN #__users AS u ON u.id = library.checked_out " .
//     " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game ".
//     " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
//     " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
//     " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
//     " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
//     (count($where) ? "  WHERE ".implode(' AND ', $where) : "") .
//     " ORDER BY library.catid, library.ordering " .
//     " LIMIT $pageNav->limitstart,$pageNav->limit;";

	$database->setQuery( $query ); 
	$cat_all = $database->loadObjectList();

	for ($i = 0; $i < count($cat_all); $i++) {
		if (is_exist_curr_and_subcategory_medias($cat_all[$i]->id)) $cat_all[$i]->display = 1;
	}
	

	$currentcat = NULL;
	// Parameters
	$menu =& new mosMenu( $database );
	$menu->load( $Itemid );
	$params =& new mosParameters( $menu->params );
	$params->def( 'header', $menu->name );
	$params->def( 'pageclass_sfx', '' );
	$params->def( 'category_name', $category->title );
	$params->def( 'show_search', '1' );
	
	//add to path category name
	constructPathway($category);
	$mainframe->appendPathWay($category->name);


	if( ($medialibrary_configuration['reviews']['show']) )
  {
		$params->def('show_lendstatus',1);
 
		if (checkAccess($medialibrary_configuration['lendrequest']['registrationlevel'],'RECURSE', userGID($my->id), $acl)) {
			$params->def( 'show_lendrequest', 1);
		}
	}

	//add for show in category picture
	if( ($medialibrary_configuration['cat_pic']['show']) ) $params->def( 'show_cat_pic', 1 );

	$params->def( 'show_rating', 1 );
	
	$params->def( 'hits', 1 );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );


	$currentcat->descrip = $category->description;
	
	// page image
	$currentcat->img = null;
	$path = $mosConfig_live_site .'/images/stories/';
	if ( $category->image != null && count($category->image) > 0) {
		$currentcat->img = $path . $category->image;
		$currentcat->align = $category->image_position;
	}

	$currentcat->header = '';
	if ( $category->name <> '' ) {
		$currentcat->header = $category->name;
	} else {
		$currentcat->header = $params->get( 'header' );
	}
	$currentcat->header = $currentcat->header . ": " . $category->title;
	


	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

//	HTML_medialibrary::displayBooks($books, $currentcat, $params, $tabclass, $catid, $sub_categories_checked);
	HTML_medialibrary::displayMedias($medias, $currentcat, $params, $tabclass, $catid, $cat_all,is_exist_subcategory_books($catid) );
}



function showItem ($id, $catid) 
{
	global $mainframe, $database, $my, $acl, $option ;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid, $medialibrary_configuration;
 
	//add to path category name
	//getting the current category informations
	$query = "SELECT * FROM #__categories WHERE id='$catid'";
       
	$database->setQuery( $query );	
	$category = $database->loadObjectList();

	$category = $category[0];

  //add to path category name
  constructPathway($category);
  $pathway =  sefRelToAbs('index.php?option=' . $option . 
	    '&task=showCategory&catid=' . $category->id . '&Itemid=' . $Itemid);
  $pathway_name =  "media"  ;
	$mainframe->appendPathWay($pathway_name,$pathway);
	$mainframe->appendPathWay(" ");

	//Record the hit
	$sql="UPDATE #__medialibrary SET hits = hits + 1 WHERE id = ". $id ."";
	$database->setQuery( $sql );
	$database->query();

	//load the Media
	$media = new mosMediaLibrary( $database );
	$media->load($id);

//print_r($media);
 //echo '<br /><br />';

  $media_type_class = '';
  switch ($media->media_type)
  {
    case 'book':
      $media_type_class = new mosMedialibrary_book($database);
      $media_type_class->load($media->media_id);
      break;
    case 'video':
      $media_type_class = new mosMedialibrary_video($database);
      $media_type_class->load($media->media_id);
      break;
    case 'music':
      $media_type_class = new mosMedialibrary_music($database);
      $media_type_class->load($media->media_id);
      break;
    case 'game':
      $media_type_class = new mosMedialibrary_game($database);
      $media_type_class->load($media->media_id);
      break;
  }
// print_r($media);
//  echo '<br /><br />';
// print_r($media_type_class); exit;

	// Parameters
	$menu =& new mosMenu( $database );
	$menu->load( $Itemid );
	$params =& new mosParameters( $menu->params );
	$params->def( 'header', $menu->name );
	$params->def( 'pageclass_sfx', '' );


	if( ( $medialibrary_configuration['lendstatus']['show'] ) ){
		$params->def( 'show_lendstatus', 1 );
		if (checkAccess($medialibrary_configuration['lendrequest']['registrationlevel'],
      'RECURSE', userGID($my->id), $acl)) {
			$params->def( 'show_lendrequest', 1);
		}
	}

	if( ($medialibrary_configuration['reviews']['show']) ){
		$params->def( 'show_reviews', 1 );
		if (checkAccess($medialibrary_configuration['reviews']['registrationlevel'],
      'RECURSE', userGID($my->id), $acl)) {
			$params->def( 'show_inputreviews', 1);
		}
	}	
	
	if( ($medialibrary_configuration['emedias']['show'] ) ){
		$params->def( 'show_emediastatus', 1 );
		if (checkAccess($medialibrary_configuration['emedias']['registrationlevel'],
      'RECURSE', userGID($my->id), $acl)) {
			$params->def( 'show_emedisrequest', 1);
		}
	} 

	if( ( $medialibrary_configuration['price']['show'] ) ){
		$params->def( 'show_pricestatus', 1 );
    $params->def( 'show_pricerequest', 1);
	}

//************   begin add button 'buy now'   ***************************
		$params->def( 'show_buy_now', 1 );
    $params->def( 'show_input_buy_now', 1);
//************   end add button 'buy now'   ********************************

	
	$params->def( 'pageclass_sfx', '' );
	$params->def( 'item_description', 1 );
	$params->def( 'lend_request', $medialibrary_configuration['lendrequest']['registrationlevel'] );
	//$params->def( 'show_emedia', $medialibrary_configuration['emedias']['show'] );
	$params->def( 'show_price', $medialibrary_configuration['price']['show'] );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );
	
	
	// page header
	$currentcat->header = $params->get( 'header' );
	$currentcat->header = $currentcat->header . ": " . $media_type_class->title;	
	
	// show the book
	HTML_medialibrary::displayMedia( $media, $media_type_class, $tabclass, $params, $currentcat );
}




function showSearchMedias($options, $catid, $option)
{

	global $mainframe, $database, $my;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid;
	
	$currentcat = NULL;
	// Parameters
	$menu =& new mosMenu( $database );
	$menu->load( $Itemid );
	$params =& new mosParameters( $menu->params );
	$params->def( 'header', $menu->name );
	$params->def( 'pageclass_sfx', '' );
	//
	$params->def( 'show_search', '1' );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

	$currentcat->descrip = _MEDIALIBRARY_SEARCH_DESC1;
  $currentcat->align = 'right';
	
	// page image
	$currentcat->img = "./components/com_medialibrary/images/medialibrary_logo.png";


	$currentcat->header = $params->get( 'header' );
	$currentcat->header = $currentcat->header . ": " . _MEDIALIBRARY_LABEL_SEARCH;
	
	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

	$categories[] = mosHTML :: makeOption('0', 'Search category');
	$database->setQuery("SELECT id AS value, name AS text FROM #__categories ".
    " WHERE section='$option' ORDER BY ordering");
	$categories = array_merge($categories, $database->loadObjectList());

	if (count($categories) < 1) {
	    mosRedirect("index2.php?option=categories&amp;section=$option&amp;err_msg=You must first create category for that section.");
	}

	$clist = mosHTML :: selectList($categories, 'catid', 'class="inputbox" size="1"', 'value', 'text', 0);


	// show thte book 
	HTML_medialibrary::showSearchMedias( $params, $currentcat, $clist , $option);

}

function searchMedias($options, $catid, $option){

	global $mainframe, $database, $my, $acl;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid, $medialibrary_configuration;
	
  $session = &JFactory::getSession();
	
  if(array_key_exists("searchtext",$_REQUEST))
  {	
    $search = mosGetParam( $_REQUEST, 'searchtext', '' );
    $session->set("poisk",$search);	
  }	
        
  $poisk_search = $session->get("poisk","default");        

	$where = array();
	
	array_push($where, "(LOWER(other_table.title) LIKE '%$search%' OR LOWER(other_table.comment) LIKE '%$search%' ".
    " OR LOWER(other_table.ext1) LIKE '%$search%' OR LOWER(other_table.ext2) LIKE '%$search%' ".
    " OR LOWER(other_table.ext3) LIKE '%$search%' )");
	array_push($where, "library.published='1'");
	array_push($where, "library.approved='1'");
	array_push($where, "library.archived=0");
	if($catid){
		array_push($where, "cc.id=$catid");
	}
	
	// getting all books for this category
/*	$query = "SELECT b.*, c.title as category_titel, c.ordering as category_ordering "
    ." FROM #__medialibrary AS b ".
		" LEFT JOIN #__categories AS c".
		" ON b.catid = c.id". 
		((count($where) ? " WHERE ".implode(' AND ', $where) : "")).
		" ORDER BY category_ordering, ordering";*/
  $selectstring = "SELECT library.id, library.media_type, library.media_id, library.fk_lendid, " .
    " cc.title AS category_titel, library.published, library.hits, library.checked_out, library.catid, ".
    " cc.ordering as category_ordering , " .
    " other_table.id as media_type_id,  other_table.title as title,  " .
    " other_table.URL as URL,  other_table.imageURL as imageURL, other_table.rating as rating  " .
    " FROM #__medialibrary AS library " .
    " LEFT JOIN #__categories AS cc ON cc.id = library.catid "  .
    " LEFT JOIN (SELECT id, title, 'game' as type,comment, URL,imageURL,rating, studio as ext1, binding as ext2, platform as ext3 FROM #__medialibrary_game ".
    " UNION all SELECT id, title, 'music' as type,comment,URL,imageURL,rating,artist as ext1, label as ext2, tracklist as ext3 FROM #__medialibrary_music " .
    " UNION all SELECT id, title, 'book' as type,comment,URL,imageURL,rating,authors as ext1, manufacturer as ext2, edition as ext3 FROM #__medialibrary_book " .
    " UNION all SELECT id, title, 'video' as type,comment,URL,imageURL,rating,actors as ext1, producers as ext2, format as ext3 FROM #__medialibrary_video) " .
    " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
    (count($where) ? "  WHERE ".implode(' AND ', $where) : "") .
    " ORDER BY category_ordering, library.ordering" ;


	$database->setQuery( $selectstring );
	$medias = $database->loadObjectList();
//print_r($database); exit;
	

	$currentcat = NULL;
	// Parameters
	$menu =& new mosMenu( $database );
	$menu->load( $Itemid );
	$params =& new mosParameters( $menu->params );
	$params->def( 'header', $menu->name );
	$params->def( 'pageclass_sfx', '' );
	$params->def( 'category_name', _MEDIALIBRARY_LABEL_SEARCH );
	$params->def( 'search_request', '1' );	
	$params->def( 'hits', 1 );
	$params->def( 'show_rating', 1 );
	
	
	if(( $medialibrary_configuration['lendstatus']['show'] )){
		$params->def( 'show_lendstatus', 1 );
		if (checkAccess( $medialibrary_configuration['lendrequest']['registrationlevel'],
      'RECURSE', userGID($my->id), $acl)) {
			$params->def( 'show_lendrequest', 1);
		}
	}

	//add for show in category picture
	if(($medialibrary_configuration['cat_pic']['show'])) $params->def('show_cat_pic',1);

	$params->def( 'back_button', $mainframe->getCfg('back_button'));

	$currentcat->descrip = _MEDIALIBRARY_SEARCH_DESC2;
	$currentcat->align = 'right';
	// page image
	$currentcat->img = "./components/com_medialibrary/images/medialibrary_logo.png";

	$currentcat->header = $params->get( 'header' );
	$currentcat->header = $currentcat->header .":". _MEDIALIBRARY_LABEL_SEARCH;
	
	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

	HTML_medialibrary::displayMedias($medias, $currentcat, $params, $tabclass, $catid, null,false);
//	HTML_medialibrary::displayBooks($books, $currentcat, $params, $tabclass, $catid, $cat_all);
}

function checkAccess( $accessgroupid, $recurse, $usersgroupid, $acl) {
	
	//parse usergroups
	$tempArr = array();
	$tempArr = explode(',',$accessgroupid);
//	print_r($tempArr);echo ':<BR />'; print_r($usersgroupid);
//	echo ':<BR />';
	for($i = 0;$i<count($tempArr);$i++)
	{
	 if($tempArr[$i] == $usersgroupid || $tempArr[$i]==-2){
		return 1;
		}else 
		if($recurse == 'RECURSE'){
			$groupchildren=array();
			$groupchildren=$acl->get_group_children( $tempArr[$i], 'ARO', $recurse );
			if(is_array($groupchildren)&& count($groupchildren) > 0) 
				if ( in_array($usersgroupid, $groupchildren) )
					return 1;
					}
		
	}
        
		//deny access
     		return 0;
	  
}

function userGID($oID){
  	global $database,$ueConfig;
	if($oID > 0) {
		$query = "SELECT gid FROM #__users WHERE id = '".$oID."'";
		$database->setQuery($query);
		$gid = $database->loadResult();
		return $gid;
	}
	else return 0;
}

?>
